#!/usr/bin/python3
# -*- coding: utf-8 -*-

import logging, json
from aiohttp import web
from aiohttp.web import middleware
from aioweb import corelib

import main

@middleware
async def middleware(request, handler):
    user = await main.cookie2user(request)
    if user:
        request.__user__ = user
    resp = await handler(request)
    # print(handler.__name__)
    try:
        resp_data = ''
        params = await corelib.parse_param(request)
        if isinstance(resp, dict):
            if hasattr(handler, '__template__'):
                if user:
                    resp['__user__'] = user.single_to_dict()
                resp_data = json.dumps(resp)
                resp = web.Response(body=request.app['__templating__'].get_template(getattr(handler, '__template__')).render(**resp).encode('utf-8'))
                resp.content_type = 'text/html;charset=utf-8'
            else:
                resp = web.json_response(resp)
        if (resp.content_type == 'application/json') :
            resp_data = resp.text
        # logging.info('-' * 65)
        # logging.info('parmas: %s' % params)
        # logging.info('request.remote: %s' % request.remote)
        # logging.info('request.line: %s' % ('%s %s HTTP/%s.%s' % (request.method, request.path_qs, request.version.major, request.version.minor)))
        # logging.info('request.headers: %s' % {k: v for k, v in request.headers.items()})
        # logging.info('-' * 35)
        # logging.info('status line:  HTTP/%s.%s %s %s' % (request.version.major, request.version.minor, resp.status, resp.reason))
        # logging.info('response.headers: %s' % {k: v for k, v in resp.headers.items()})
        # logging.info('response.data: %s' % resp_data)
        # logging.info('-' * 65)
        if not request.path_qs.startswith('/records'):
            main.record(request, resp, handler, params, resp_data)
    except BaseException as e:
        logging.error('[ERROR] datars: %s\n' % corelib.printException(e))
        resp = web.json_response({'code': -1, 'msg': 500})
    return resp

